package com.wgchao.amc.service.impl;

import com.wgchao.amc.common.EvaluateInfo;
import com.wgchao.amc.common.ResultCommon;
import com.wgchao.amc.entity.autho.SysAuthoGroup;
import com.wgchao.amc.entity.autho.SysAuthoGroupFunc;
import com.wgchao.amc.entity.base.SysBaseFunc;
import com.wgchao.amc.entity.base.SysBaseGroup;
import com.wgchao.amc.entity.base.SysBaseMenu;
import com.wgchao.amc.entity.menu.SysMenuProject;
import com.wgchao.amc.mapstruct.dto.SysAuthoGroupDTO;
import com.wgchao.amc.mapstruct.dto.SysAuthoGroupFuncDTO;
import com.wgchao.amc.mapstruct.mapper.SysAuthoGroupFuncMapper;
import com.wgchao.amc.mapstruct.mapper.expand.SysAuthoGroupMapperExpand;
import com.wgchao.amc.repository.autho.SysAuthoGroupFuncRepository;
import com.wgchao.amc.repository.autho.SysAuthoGroupRepository;
import com.wgchao.amc.repository.base.SysBaseFuncRepository;
import com.wgchao.amc.repository.base.SysBaseGroupRepository;
import com.wgchao.amc.repository.base.SysBaseMenuRepository;
import com.wgchao.amc.repository.menu.SysMenuProjectRepository;
import com.wgchao.amc.service.EvaluateService;
import com.wgchao.amc.service.GAService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassName: GAServiceImpl
 * @author: wgchao
 * @createTime: 2019/10/31 9:06 AM
 * @Description: 部门权限管理
 */
@Service
@Transactional
public class GAServiceImpl implements GAService, EvaluateService {
    @Autowired
    private SysBaseGroupRepository groupRepository;
    @Autowired
    private SysMenuProjectRepository projectRepository;
    @Autowired
    private SysBaseMenuRepository menuRepository;
    @Autowired
    private SysBaseFuncRepository funcRepository;
    @Autowired
    private SysAuthoGroupRepository authoGroupRepository;
    @Autowired
    private SysAuthoGroupFuncRepository authoGroupFuncRepository;
    @Autowired
    private SysAuthoGroupMapperExpand authoGroupMapperExpand;
    @Autowired
    private SysAuthoGroupFuncMapper authoGroupFuncMapper;

    /**
     * 为部门分配菜单权限
     * @param groupId 部门ID
     * @param proMark 项目标示
     * @param gaDTOs 菜单权限
     * @return
     * @throws Exception
     */
    @Override
    public ResultCommon<List<SysAuthoGroupDTO>> assign(Long groupId, String proMark, List<SysAuthoGroupDTO> gaDTOs) throws Exception {
        //数据检校
        EvaluateInfo evaluateInfo = evaluate(gaDTOs, gads -> {
            List<SysAuthoGroupDTO> gaDtos = (List<SysAuthoGroupDTO>) gads;
            Optional<SysBaseGroup> groupOptional = groupRepository.findById(groupId);
            if(!groupOptional.isPresent()){
                return new EvaluateInfo(false, "部门不存在");
            }
            SysBaseGroup group = groupOptional.get();
            if(group.isDel()){
                return new EvaluateInfo(false, "部门已删除");
            }
            SysMenuProject project = projectRepository.findFirstByProMark(proMark);
            if(project == null){
                return new EvaluateInfo(false, "项目不存在");
            }
            for(SysAuthoGroupDTO groupDTO:gaDtos){
                Optional<SysBaseMenu> menuOptional = menuRepository.findById(groupDTO.getMenuId());
                if(!menuOptional.isPresent()){
                    return new EvaluateInfo(false, groupDTO.getMenuId()+"菜单不存在");
                }
                SysBaseMenu menu = menuOptional.get();
                if(!menu.getProMark().equals(proMark)){
                    return new EvaluateInfo(false, menu.getMenuName()+"菜单不再该项目中");
                }
                List<SysAuthoGroupFuncDTO> groupFuncs = groupDTO.getGroupFuncs();
                if(groupFuncs!=null && !groupFuncs.isEmpty() ){
                    for(SysAuthoGroupFuncDTO funcDTO:groupFuncs){
                        Optional<SysBaseFunc> funcOptional = funcRepository.findById(funcDTO.getFuncId());
                        if(!funcOptional.isPresent()){
                            return new EvaluateInfo(false, funcDTO.getFuncId()+"功能操作不存在");
                        }
                    }
                }
            }
            return new EvaluateInfo(true, null);
        });
        if(!evaluateInfo.isSuccess()){
            return ResultCommon.fail(evaluateInfo.getMsg());
        }

        //删除原有的菜单权限
        List<SysAuthoGroup> oldGas = authoGroupRepository.findAllByGroupIdAndProMarkOrderById(groupId, proMark);
        if(oldGas!=null && !oldGas.isEmpty()){
            for(SysAuthoGroup oldGa:oldGas){
                List<SysAuthoGroupFunc> gafuncs = authoGroupFuncRepository.findAllByAgId(oldGa.getId());
                if(gafuncs!=null && !gafuncs.isEmpty()){
                    authoGroupFuncRepository.deleteAll(gafuncs);
                }
            }
            authoGroupRepository.deleteAll(oldGas);
        }

        //设置新的菜单权限信息
        for(SysAuthoGroupDTO authoGroupDTO:gaDTOs){
            SysAuthoGroup authoGroup = authoGroupMapperExpand.toEntity(authoGroupDTO);
            authoGroup.setGroupId(groupId);
            authoGroup.setProMark(proMark);
            authoGroup.setCreateTime(new Date());
            authoGroup = authoGroupRepository.save(authoGroup);

            List<SysAuthoGroupFuncDTO> groupFuncs = authoGroupDTO.getGroupFuncs();
            if(groupFuncs!=null && !groupFuncs.isEmpty() ){
                //保存菜单功能信息
                for(SysAuthoGroupFuncDTO funcDTO:groupFuncs){
                    SysAuthoGroupFunc authoGroupFunc = authoGroupFuncMapper.toEntity(funcDTO);
                    authoGroupFunc.setAgId(authoGroup.getId());
                    authoGroupFunc = authoGroupFuncRepository.save(authoGroupFunc);
                }
            }
        }

        List<SysAuthoGroup> authoGroups = authoGroupRepository.findAllByGroupIdAndProMarkOrderById(groupId, proMark);
        gaDTOs = authoGroups.stream().map(sysAuthoGroup -> {
            SysAuthoGroupDTO authoGroupDTO = authoGroupMapperExpand.toDTO(sysAuthoGroup);
            authoGroupDTO = authoGroupMapperExpand.getFuncInfo(authoGroupDTO);
            return authoGroupDTO;
        }).collect(Collectors.toList());
        return ResultCommon.success().setData(gaDTOs);
    }

    /**
     * 查询部门菜单权限
     * @param groupId 部门ID
     * @param proMark 项目标示
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(readOnly = true)
    public ResultCommon<List<SysAuthoGroupDTO>> search(Long groupId, String proMark) throws Exception {
        List<SysAuthoGroup> authoGroups = authoGroupRepository.findAllByGroupIdAndProMarkOrderById(groupId, proMark);
        List<SysAuthoGroupDTO> gaDTOs = authoGroups.stream().map(sysAuthoGroup -> {
            SysAuthoGroupDTO authoGroupDTO = authoGroupMapperExpand.toDTO(sysAuthoGroup);
            authoGroupDTO = authoGroupMapperExpand.getFuncInfo(authoGroupDTO);
            return authoGroupDTO;
        }).collect(Collectors.toList());
        return ResultCommon.success().setData(gaDTOs);
    }
}
